package com.pdsu.graduation_design.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class JsonUtil {

    private final static ObjectMapper objectMapper = new ObjectMapper();

    public static ObjectMapper getInstance() {

        return objectMapper;
    }



  public static String ObjToJson(Object obj) throws JsonProcessingException {



        return objectMapper.writeValueAsString(obj);
    }

    public static  <T> T JsonToObj(String json,Class<T> clazz) throws JsonProcessingException {



        return objectMapper.readValue(json, clazz);
    }

    /**
     * json array string convert to list with javaBean
     */
    public static <T> List<T> json2list(String jsonArrayStr, Class<T> clazz)
            throws Exception {
        List<Map<String, Object>> list = (List<Map<String, Object>>) objectMapper.readValue(jsonArrayStr, new TypeReference<List<T>>() {
        });

        List<T> result = new ArrayList<T>();
        for (Map<String, Object> map : list) {
            result.add(map2pojo(map, clazz));
        }
        return result;
    }
    /**
     * map convert to javaBean
     */
    public static <T> T map2pojo(Map map, Class<T> clazz) {
        return objectMapper.convertValue(map, clazz);
    }

    public static <T> String ListToJson(List<T> list) throws JsonProcessingException {


        String json=objectMapper.writeValueAsString(list);
        JsonNode jsonNode=objectMapper.readTree(json);
        return jsonNode.toString();
    }




}
